package com.iedu.demo.lgq.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.iedu.demo.lgq.entity.TbUser;
import com.iedu.demo.lgq.entity.TbUserAddress;
import com.iedu.demo.lgq.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("logic/sysuser")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    // 用户登录
    @RequestMapping(value = "login", method = {RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "用户登录")
    public SaResult login(String userName, String password) {
        TbUser currentUser = userService.login(userName, password);
        if (currentUser == null) {
            return SaResult.code(400).setMsg("用户不存在或密码错误");
        }
        String userId = currentUser.getUserName();
        StpUtil.login(userId);
        StpUtil.getSession().set("current", userId);
        return SaResult.code(200).setMsg(StpUtil.getTokenValue()).setData(currentUser);
    }

    // 用户注册
    @RequestMapping(value = "add", method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "用户注册")
    public SaResult addUser(TbUser tbUser) {
        if (tbUser.getUserName() == null || tbUser.getPassword() == null) {
            return SaResult.code(400).setMsg("用户名或密码不能为空");
        }

        TbUser newUser = new TbUser();
        newUser.setUserName(tbUser.getUserName());
        newUser.setPassword(tbUser.getPassword());
        // 调用 service 层注册
        userService.addUser(tbUser);

        // 返回注册成功的信息
        return SaResult.code(200).setMsg("注册成功");
    }

    // 用户退出
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @Operation(summary = "用户退出")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.code(200).setMsg("退出成功");
    }

    // 获取当前用户信息
    @RequestMapping(value = "current", method = RequestMethod.GET)
    @Operation(summary = "获取当前用户信息")
    public SaResult getCurrentUser() {
        // 获取当前用户的登录信息
        String currentUser = (String) StpUtil.getSession().get("current");

        // 获取当前用户的 Token
        String token = StpUtil.getTokenValue(); // 获取当前的 Token

        // 如果 Token 为 null，则返回空字符串
        if (token == null) {
            token = "";
        }

        // 将用户信息和 Token 一起返回
        return SaResult.code(200)
                .setData(currentUser)  // 返回当前用户信息
                .set("token", token);  // 还返回 Token
    }



    // 获取所有用户信息
    @RequestMapping(value = "all", method = RequestMethod.GET)
    @Operation(summary = "获取所有用户信息")
    public SaResult findAll() {
        return SaResult.code(200).setData(userService.findAll());
    }

    // 根据条件查询用户信息
    @RequestMapping(value = "findByWhere", method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "根据条件查询用户信息")
    public SaResult findByWhere(TbUser sysUser) {
        return SaResult.code(200).setData(userService.findByWhere(sysUser));
    }

    // 更新用户状态
    @RequestMapping(value = "updateStatus", method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "更新用户状态")
    public SaResult updateStatus(@RequestParam String userName, @RequestParam int state) {
        boolean success = userService.updateUserStatus(userName, state);
        if (success) {
            return SaResult.code(200).setMsg("更新成功");
        } else {
            return SaResult.code(400).setMsg("用户不存在");
        }
    }

    // 更新用户头像
    @RequestMapping(value = "updateAvatar", method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "更新用户头像")
    public SaResult updateAvatar(@RequestParam String userId, @RequestParam String avatarUrl) {
        boolean success = userService.updateUserAvatar(userId, avatarUrl);
        if (success) {
            return SaResult.code(200).setMsg("头像更新成功");
        } else {
            return SaResult.code(400).setMsg("更新失败");
        }
    }

    // 邮箱验证
    @RequestMapping(value = "verifyEmail", method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "验证邮箱")
    public SaResult verifyEmail(@RequestParam String userId, @RequestParam String email) {
        boolean success = userService.verifyEmail(userId, email);
        if (success) {
            return SaResult.code(200).setMsg("邮箱验证成功");
        } else {
            return SaResult.code(400).setMsg("邮箱验证失败");
        }
    }
//动态更新用户详细信息
    @RequestMapping(value = "updateDetails", method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "动态更新用户详细信息")
    public SaResult updateDetails(@RequestBody TbUser user) {
        boolean success = userService.updateUserDetails(user);
        if (success) {
            return SaResult.code(200).setMsg("用户信息更新成功");
        } else {
            return SaResult.code(400).setMsg("用户信息更新失败");
        }
    }
    // 添加用户收货地址
    @PostMapping(value = "/addAddress")
    @Operation(summary = "添加用户收货地址")
    public SaResult addUserAddress(
            @RequestParam String userName,          // 用户
            @RequestParam String regionId,       // 省
            @RequestParam String cityId,       // 区
            @RequestParam String address,   // 详细地址
            @RequestParam String tel,
            @RequestParam String realName) {
        // 调用服务层的addUserAddress方法
        boolean isAdded = userService.addUserAddress(userName, regionId, cityId, address, tel, realName);

        // 判断地址添加是否成功
        if (isAdded) {
            return SaResult.code(200).setMsg("收货地址添加成功");
        } else {
            return SaResult.code(400).setMsg("用户不存在，无法添加收货地址");
        }
    }
    // 获取用户的所有收货地址
    @GetMapping("/addresses/{userName}")
    @Operation(summary = "获取用户的所有收货地址")
    public ResponseEntity<?> getUserAddresses(@PathVariable String userName) {
        // 调用 UserService 获取用户的所有收货地址
        List<TbUserAddress> addresses = userService.getUserAddresses(userName);

        if (addresses == null || addresses.isEmpty()) {
            // 如果没有找到地址，则返回 404 Not Found
            return ResponseEntity.status(404).body("No addresses found for user: " + userName);
        }

        // 如果找到了收货地址，返回 200 OK 和地址数据
        return ResponseEntity.ok(addresses);
    }


}
